package com.zhou.test.spring.secrity.security.remember;

import com.zhou.common.operator.log.core.constant.OperateActionEnum;
import com.zhou.common.operator.log.core.model.OperateLogInfo;
import com.zhou.common.operator.log.core.model.PrincipalInfo;
import com.zhou.common.operator.log.core.resolver.ClientInfoResolver;
import com.zhou.common.operator.log.core.service.OperateLogStorageService;
import com.zhou.test.spring.secrity.content.ServletUtil;
import com.zhou.test.spring.secrity.content.UserContext;
import com.zhou.test.spring.secrity.entity.SysUser;
import com.zhou.test.spring.secrity.model.security.MyUserDetails;
import com.zhou.test.spring.secrity.service.impl.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author xianfeng
 * @date 2023/5/13 17:31
 */
@Slf4j
@Component
public class RememberMeLoginSuccessListener {

    @Resource
    private OperateLogStorageService logService;

    @Resource
    private ClientInfoResolver clientInfoResolver;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @EventListener
    public void handleMyEventMap(InteractiveAuthenticationSuccessEvent logoutSuccessEvent) {

        log.info("登录成功");
        MyUserDetails currentUser = UserContext.currentUser();
        //更新最后一次访问时间
        SysUser sysUser = new SysUser();
        sysUser.setUserId(currentUser.getSysUser().getUserId());
        sysUser.setLoginDate(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        OperateLogInfo logInfo = new OperateLogInfo();
        logInfo.setClientInfo(this.clientInfoResolver.resolveClientInfo(ServletUtil.getRequest()));
        logInfo.setAddTime(new Date());

        PrincipalInfo principalInfo = new PrincipalInfo();
        principalInfo.setUserId(currentUser.getUserId() + "");
        principalInfo.setUserName(currentUser.getUsername());
        principalInfo.setUserPhone(currentUser.getPhone());
        principalInfo.setOrgId(currentUser.getCurrOrgId() + "");
        principalInfo.setOrgName(currentUser.getCurrOrgName() + "");
        logInfo.setPrincipal(principalInfo);
        logInfo.setAction(OperateActionEnum.LOGIN.getAction());
        logInfo.setOperatingInstruction("登录成功: rememberme");
        this.logService.append(logInfo);
    }
}
